<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SVG Example</title>
</head>
<style>
    #canvasBackground {
        background: rgba(0, 0, 0, 0.1);
    }

    .tools {
        position: fixed;
        top: 10px;
        right: 20px;
    }
</style>

<body>
    <svg id="canvasBackground" width="1000" height="600"></svg>
    <div class="tools">
        <button id="createRectBtn">创建</button>
        <select name="" id="select">
            <option value="25">25</option>
            <option value="50">50</option>
            <option value="75">75</option>
            <option value="100">100</option>
            <option value="150">150</option>
            <option value="200">200</option>
        </select>
    </div>
    <script>
        const arr = [25, 50, 75, 100, 150, 200]
        let index = 0
        let ratioPercentage = 0;
        const dpmm = 96 / 25.4;
        const svg = document.getElementById('canvasBackground');
        const select = document.getElementById('select');
        const createRectBtn = document.getElementById("createRectBtn");

        // 定义变量用于存储鼠标移动时的初始位置
        let isDragging = false;
        let pendingAnimationFrame = false;
        let mouseX, mouseY;

        // 定义变量用于存储事件监听器
        let eventListeners = [];

        // 监听鼠标按下事件
        addEventListenerWithTracking(document, 'mousedown', function (event) {
            // 判断是否是鼠标中间按钮按下（鼠标中键的按钮值是2）
            if (event.button === 1) {
                console.log(index);
                if (index === 5) index = 0
                handleSelectChange(event, arr[index])
                index += 1
            }
        })

        function addEventListenerWithTracking(element, event, handler) {
            element.addEventListener(event, handler);
            eventListeners.push({ element, event, handler });
        }

        function removeAllEventListeners() {
            eventListeners.forEach(({ element, event, handler }) => {
                element.removeEventListener(event, handler);
            });
            eventListeners = [];
        }

        function getMousePosition(event, svg) {
            const ctm = svg.getScreenCTM();
            return {
                x: (event.clientX - ctm.e) / ctm.a,
                y: (event.clientY - ctm.f) / ctm.d
            };
        }
        const handleSelectChange = (event, ratioPercentage) => {
            const newRatio = ratioPercentage / 100;
            const targetZoom = newRatio * dpmm;
            svg.style.transform = `scale(${targetZoom})`;
        }
        addEventListenerWithTracking(select, "change", (e) => {
            ratioPercentage = Number(select.options[select.selectedIndex].value);
            handleSelectChange(event, ratioPercentage)
        });

        // creactConcentrator
        function createSvgConcentrator(svg) {
            // 获取原始SVG容器的宽度和高度
            const containerWidth = svg.clientWidth;
            const containerHeight = svg.clientHeight;

            // 计算缩放比例（20分之一）
            const scale = 1 / 5;

            // 计算新的SVG容器的宽度和高度
            const newWidth = containerWidth * scale;
            const newHeight = containerHeight * scale;

            // 计算矩形的宽度和高度（按照13:8的比例）
            const ratio = 13 / 8;
            let rectWidth, rectHeight;
            if (newWidth / newHeight > ratio) {
                rectHeight = newHeight;
                rectWidth = rectHeight * ratio;
            } else {
                rectWidth = newWidth;
                rectHeight = rectWidth / ratio;
            }

            // 创建SVG元素
            const svgContainer = document.createElementNS("http://www.w3.org/2000/svg", "svg");
            svgContainer.setAttribute("width", rectWidth);
            svgContainer.setAttribute("height", rectHeight);
            svgContainer.setAttribute("id", 'svg-thickness-concentrator');
            svgContainer.setAttribute("style", "background: rgba(0,0,0,0.4); cursor: grab;");
            document.body.appendChild(svgContainer); // 将SVG元素添加到页面中


            // 创建一个新的矩形组元素
            const rectGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
            rectGroup.setAttribute('x', '100');
            rectGroup.setAttribute('y', '100');

            // 创建一个矩形元素
            const rectangle = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
            rectangle.setAttribute('x', '0');
            rectangle.setAttribute('y', '0');
            rectangle.setAttribute('width', rectWidth);
            rectangle.setAttribute('height', rectHeight);
            rectangle.setAttribute('fill', 'rgba(255,255,255,0.2)'); // 设置填充色

            // 定义路径数据
            const pathData = `
                M 0,0 L 25,0 M 0,0 L 0,25
                M ${rectWidth},0 L ${rectWidth - 25},0 M ${rectWidth},0 L ${rectWidth},25
                M 0,${rectHeight} L 25,${rectHeight} M 0,${rectHeight} L 0,${rectHeight - 25}
                M ${rectWidth},${rectHeight} L ${rectWidth - 25},${rectHeight} M ${rectWidth},${rectHeight} L ${rectWidth},${rectHeight - 25}
            `;

            // 创建路径元素
            const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
            path.setAttribute('d', pathData);
            path.setAttribute('stroke', '#FF5C02');
            path.setAttribute('stroke-width', '4');
            path.setAttribute('fill', 'none');

            // 将路径元素添加到矩形组中
            rectGroup.appendChild(rectangle);
            rectGroup.appendChild(path);

            // 将矩形组元素添加到SVG容器中
            svgContainer.appendChild(rectGroup);

            return svgContainer;
        }

        // 定义函数用于处理矩形的移动
        function updateRectPosition(rect) {
            return function () {
                // 获取SVG元素的宽度和高度
                let svgWidth = parseInt(svg.getAttribute("width"));
                let svgHeight = parseInt(svg.getAttribute("height"));

                // 获取矩形的大小
                let rectWidth = parseInt(rect.getAttribute("width"));
                let rectHeight = parseInt(rect.getAttribute("height"));

                // 计算鼠标位置相对于SVG的坐标
                let newX = mouseX - rectWidth / 2;
                let newY = mouseY - rectHeight / 2;

                // 确保矩形不超出SVG边界
                newX = Math.max(0, Math.min(svgWidth - rectWidth, newX));
                newY = Math.max(0, Math.min(svgHeight - rectHeight, newY));

                // 更新矩形的位置
                rect.setAttribute("x", newX);
                rect.setAttribute("y", newY);

                pendingAnimationFrame = false;

                if (isDragging) {
                    requestAnimationFrame(updateRectPosition(rect));
                }
            };
        }

        // 定义函数用于创建矩形
        function createRect(svg) {
            // 检查SVG中是否已经存在矩形
            if (svg.getElementById("svg-thickness-concentrator")) {
                console.log("矩形已存在，无需创建新的矩形。");
                return;
            }

            const detectionThicknessDom = createSvgConcentrator(svg);
            const width = detectionThicknessDom.getAttribute("width")
            const svgWidth = svg.getAttribute("width")
            detectionThicknessDom.setAttribute('x', svgWidth - width);

            // 添加鼠标移入SVG事件监听器
            addEventListenerWithTracking(svg, "mouseenter", function (event) {
                isDragging = true;
                const pos = getMousePosition(event, svg);
                mouseX = pos.x;
                mouseY = pos.y;
                requestAnimationFrame(updateRectPosition(detectionThicknessDom));
            });

            // 添加鼠标移出SVG事件监听器
            addEventListenerWithTracking(svg, "mouseleave", function (event) {
                isDragging = false;
            });

            // 添加鼠标移动事件监听器
            addEventListenerWithTracking(svg, "mousemove", function (event) {
                if (isDragging) {
                    const pos = getMousePosition(event, svg);
                    mouseX = pos.x;
                    mouseY = pos.y;
                    if (!pendingAnimationFrame) {
                        pendingAnimationFrame = true;
                        requestAnimationFrame(updateRectPosition(detectionThicknessDom));
                    }
                }
            });

            // 添加矩形点击事件监听器
            addEventListenerWithTracking(detectionThicknessDom, "click", function () {
                const detectionThicknessDomInfo = {
                    x: detectionThicknessDom.getAttribute("x"),
                    y: detectionThicknessDom.getAttribute("y"),
                    width: detectionThicknessDom.getAttribute("width"),
                    height: detectionThicknessDom.getAttribute("height"),
                    fill: detectionThicknessDom.getAttribute("fill")
                };
                console.log("Rect Information:", detectionThicknessDomInfo);

                // 移除所有事件监听器
                removeAllEventListeners();

                // 销毁矩形
                detectionThicknessDom.parentNode.removeChild(detectionThicknessDom);
            });

            // 添加矩形右键点击事件监听器
            addEventListenerWithTracking(detectionThicknessDom, "contextmenu", function (event) {
                event.preventDefault(); // 阻止默认右键菜单

                // 移除所有事件监听器
                removeAllEventListeners();

                // 销毁矩形
                detectionThicknessDom.parentNode.removeChild(detectionThicknessDom);
            });

            // 将矩形添加到SVG元素中
            svg.appendChild(detectionThicknessDom);
        }

        // 为按钮添加点击事件监听器
        createRectBtn.addEventListener("click", () => createRect(svg));
    </script>
</body>

</html>